package com.wtb.javatool.service.impl;

import com.wtb.javatool.dao.AchievementMapper;
import com.wtb.javatool.dao.EvaluationMapper;
import com.wtb.javatool.dao.SubmissionMapper;
import com.wtb.javatool.service.SubmissionService;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@Service
public class SubmissionServiceImpl implements SubmissionService {
    private final SubmissionMapper submissionMapper;
    private final EvaluationMapper evaluationMapper;
    private final AchievementMapper achievementMapper;

    public SubmissionServiceImpl(SubmissionMapper submissionMapper, EvaluationMapper evaluationMapper, AchievementMapper achievementMapper) {
        this.submissionMapper = submissionMapper;
        this.evaluationMapper = evaluationMapper;
        this.achievementMapper = achievementMapper;
    }

    /**
     * 批量删除提交记录和对应的提交文件和评论记录
     *
     * @param submissionIds 提交记录id列表
     */
    public void deleteSubmissions(List<Long> submissionIds) {
        //删除对应的评价记录
        evaluationMapper.batchDeleteEvaluations(submissionIds);
        //获取对应的提交文件的地址
        List<String> urls = achievementMapper.bathFindAchievements(submissionIds);
        for (String url : urls) {
            try {
                Path path = Paths.get(url);
                Files.delete(path);
            } catch (IOException e) {
                System.err.println("删除提交文件时出错: " + e.getMessage());
            }
        }
        //删除对应的提交文件记录
        achievementMapper.batchDeleteAchievements(submissionIds);
        submissionMapper.batchDeleteSubmissions(submissionIds);
    }
}
